//
//  BVAppDelegate.m
//  AFNetworking
//
//  Created by 崔晋 on 2019/8/11.
//

#import "BVAppDelegate.h"
#import "BVBaseNavigationController.h"
#import "BVBaseRouter.h"
#import "SDWebImage.h"
#import "WXApi.h"
#import "BVService.h"
#import "AFNetWorking.h"
#import "BVUserDefault.h"
#import <UMShare/UMShare.h>
#import <UMCommon/UMConfigure.h>
#import <Bugly/Bugly.h>

@interface BVAppDelegate ()<WXApiDelegate>



@end

@implementation BVAppDelegate

+ (instancetype)shareInstance {
    static BVAppDelegate *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[BVAppDelegate alloc] init];
    });
    return instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setRootViewController) name:BV_NOTIFICATION_LOGIN_SUCCESS_KEY object:nil];
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [Bugly startWithAppId:kBuglyAppId];
    [WXApi registerApp:kWechatAPPId universalLink:kUniversalLink];
    [self configShare];
    [self setRootViewController];
    [self addLaunchAnimated];
    return YES;
}

- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
 restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    return [WXApi handleOpenUniversalLink:userActivity delegate:self];
}

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    [[UMSocialManager defaultManager] handleOpenURL:url options:options];
    return [WXApi handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    [[UMSocialManager defaultManager] handleOpenURL:url];
    return [WXApi handleOpenURL:url delegate:self];
}


- (void)setRootViewController {
    if (![BVUser shareInstance].isLogin) {
        self.recordWindow.rootViewController = [BVBaseRouter viewControllerWithUrl:@"login/login_page" properties:@{}];
    }else {
        self.recordWindow.rootViewController = self.tabBarController;
    }
}

- (void)addLaunchAnimated {
    NSBundle *bundle = [BVBundle bundleWithClass:[self class] name:BV_BUNDLE_ENTRANCE_MODULE];
    NSMutableArray<UIImage *> *images = [NSMutableArray array];
    CGFloat scale = 0;
    for (int i = 1; i < 48; i++) {
        UIImage *image = [UIImage bv_imageNamed:[NSString stringWithFormat:@"1-%d.jpg", i] bundle:bundle];
        [images addObject:image];
        scale = image.size.width / image.size.height;
    }
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_HEIGHT * scale, kSCREEN_HEIGHT)];
    imageV.center = CGPointMake(kSCREEN_WIDTH / 2.0, kSCREEN_HEIGHT / 2.0);
    imageV.animationImages = images.copy;
    imageV.animationRepeatCount = 0;
    imageV.animationDuration = 3.5;
    [imageV startAnimating];
    [self.recordWindow addSubview:imageV];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [imageV removeFromSuperview];
    });
}

- (void)configShare {
    [UMConfigure initWithAppkey:@"5dbbfe940cafb27b980006c7" channel:@"app store"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kWechatAPPId appSecret:kWechatSecret redirectURL:@"http://mobile.umeng.com/social"];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:kWechatAPPId appSecret:kWechatSecret redirectURL:@"http://mobile.umeng.com/social"];
}

- (void)onReq:(BaseReq *)req {
    
}

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {
        SendAuthResp *response = (SendAuthResp *)resp;
        if (response.code.length > 0) {
            [[BVService shareInstance] get:@"wechat/auth" param:@{@"code": response.code, @"source": @"ios-app"} complete:^(BOOL success, id  _Nullable response) {
                if (success) {
                    if (response[@"data"][@"token"] != nil) {
                        [BVUser sharedInstanceWith:response];
                        [[BVUserDefault standardUserDefaults] setBool:YES forKey:BV_LOGIN_USER_DEFAULT_KEY];
                        [[NSNotificationCenter defaultCenter] postNotificationName:BV_NOTIFICATION_LOGIN_SUCCESS_KEY object:nil];
                    }else {
                        NSString *unionid = response[@"data"][@"unionid"];
                        [[NSNotificationCenter defaultCenter] postNotificationName:BV_WECHAT_LOGIN_NEED_BIND_PHONE_NOTIFICATION_KEY object:unionid userInfo:nil];
                    }
                }
            }];
        }
    }
    
}

- (NSArray<UIViewController *> *)buildViewControllers {
    NSArray<UIViewController *> *vcs = @[[BVBaseRouter viewControllerWithUrl:@"home/home_page" properties:nil],
                     [BVBaseRouter viewControllerWithUrl:@"home/play_ground" properties:nil],
                     [BVBaseRouter viewControllerWithUrl:@"home/qrcode" properties:nil],
                     [BVBaseRouter viewControllerWithUrl:@"home/favorite" properties:nil],
                     [BVBaseRouter viewControllerWithUrl:@"home/personal" properties:nil]];
    NSArray *images = @[@"tabbar_home", @"tabbar_playground", @"tabbar_qrcode", @"tabbar_favorite", @"tabbar_personal"];
    [vcs enumerateObjectsUsingBlock:^(UIViewController *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImage *image = [[[UIImage bv_imageNamed:images[idx] bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_ENTRANCE_MODULE]] imageWithColor:[UIColor colorFromHexString:@"#ed633e"]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        UIImage *selectImage = [[image imageWithColor:[UIColor colorFromHexString:@"#ffffff"]] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [obj.tabBarItem setImage:image];
        [obj.tabBarItem setSelectedImage:selectImage];
        
        if (@available(iOS 10.0, *)) {
            [obj.tabBarController.tabBar setUnselectedItemTintColor:[UIColor whiteColor]];
        } else {
        }
        [obj.tabBarController.tabBar setTintColor:[UIColor colorFromHexString:@"#ed633e"]];
        
        obj.tabBarController.tabBar.barTintColor = [UIColor colorFromHexString:@"#ed633e"];
    }];
    return vcs;
}

- (BVTabBarViewController *)tabBarController {
    if (!_tabBarController) {
        _tabBarController = [[BVTabBarViewController alloc] init];
        
        
        
        _tabBarController.viewControllers = [self buildViewControllers];
    }
    return _tabBarController;
}

@end
